<template>
  <el-dialog
    v-model="dialogVisible"
    :title="dialogTitle"
    width="90%"
    :before-close="handleClose"
    :close-on-click-modal="false"
    :destroy-on-close="false"
    :append-to-body="true"
    :show-close="true"
    :modal="true"
    :lock-scroll="true"
    :close-on-press-escape="true"
    :center="false"
    :draggable="false"
    :resize="false"
    :z-index="2000"
  >
    <!-- 调试信息 -->
    <div style="background: #f0f9ff; padding: 10px; margin-bottom: 10px; border-radius: 4px; font-size: 12px;">
      <div>🔧 对话框调试信息</div>
      <div>对话框可见: {{ dialogVisible }}</div>
      <div>模式: {{ mode }}</div>
      <div>供应商数据: {{ supplier ? '有数据' : '无数据' }}</div>
      <div>props.modelValue: {{ props.modelValue }}</div>
      <div>当前时间: {{ new Date().toLocaleString() }}</div>
    </div>

    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="120px"
      class="supplier-form"
    >
      <!-- 基础信息 -->
      <el-card class="form-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span>基础信息</span>
          </div>
        </template>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="供应商编号" prop="supplierNumber">
              <el-input
                v-model="form.supplierNumber"
                placeholder="系统自动生成"
                :disabled="true"
              >
                <template #prepend>
                  <el-checkbox v-model="form.useSystemNumber" @change="handleSystemNumberChange">系统编号</el-checkbox>
                </template>
                <template #append>
                  <el-button @click="generateSupplierNumber" :disabled="!form.useSystemNumber">生成编号</el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="供应商名称" prop="supplierName">
              <el-input
                v-model="form.supplierName"
                placeholder="请输入供应商名称"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="公司名称" prop="companyName">
              <el-input
                v-model="form.companyName"
                placeholder="请输入公司名称"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="供应商等级" prop="supplierLevelId">
              <el-select
                v-model="form.supplierLevelId"
                placeholder="请选择企业等级"
                style="width: 100%"
                :loading="loadingDictionary"
                :disabled="loadingDictionary"
              >
                <el-option
                  v-for="item in supplierLevels.filter(item => item && item.id)"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
                <el-option v-if="supplierLevels.length === 0" disabled label="暂无数据" value="" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="供应商类别" prop="supplierCategoryId">
              <el-select
                v-model="form.supplierCategoryId"
                placeholder="请选择企业类别"
                style="width: 100%"
                :loading="loadingDictionary"
                :disabled="loadingDictionary"
              >
                <el-option
                  v-for="item in supplierCategories.filter(item => item && item.id)"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
                <el-option v-if="supplierCategories.length === 0" disabled label="暂无数据" value="" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="人员规模" prop="personnelScale">
              <el-select
                v-model="form.personnelScale"
                placeholder="请选择物人员规模"
                style="width: 100%"
              >
                <el-option label="1-10人" value="1-10" />
                <el-option label="11-50人" value="11-50" />
                <el-option label="51-100人" value="51-100" />
                <el-option label="101-500人" value="101-500" />
                <el-option label="500人以上" value="500+" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="营业性质" prop="businessNatureId">
              <el-select
                v-model="form.businessNatureId"
                placeholder="请选择营业性质"
                style="width: 100%"
                :loading="loadingDictionary"
                :disabled="loadingDictionary"
              >
                <el-option
                  v-for="item in businessNatures.filter(item => item && item.id)"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
                <el-option v-if="businessNatures.length === 0" disabled label="暂无数据" value="" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属行业" prop="industryId">
              <el-select
                v-model="form.industryId"
                placeholder="请选择行业"
                style="width: 100%"
                :loading="loadingDictionary"
                :disabled="loadingDictionary"
              >
                <el-option
                  v-for="item in industries.filter(item => item && item.id)"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
                <el-option v-if="industries.length === 0" disabled label="暂无数据" value="" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="注册资本" prop="registeredCapital">
              <el-input
                v-model="form.registeredCapital"
                placeholder="请输入注册资本"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所在地区" prop="locationId">
              <el-select
                v-model="form.locationId"
                placeholder="请选择所在地区"
                style="width: 100%"
                :loading="loadingDictionary"
                :disabled="loadingDictionary"
              >
                <el-option
                  v-for="item in locations.filter(item => item && item.id)"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
                <el-option v-if="locations.length === 0" disabled label="暂无数据" value="" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="公司地址" prop="companyAddress">
    <BaiduMapSelector
                v-model="form.companyAddress"
      @location-selected="handleCompanyAddressSelected"
    />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="注册地址" prop="registeredAddress">
              <el-input
                v-model="form.registeredAddress"
                placeholder="请输入注册地址"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="统一信用代码" prop="unifiedSocialCreditCode">
              <el-input
                v-model="form.unifiedSocialCreditCode"
                placeholder="请输入统一信用代码"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="isEnabled">
              <el-switch
                v-model="form.isEnabled"
                active-text="启用"
                inactive-text="禁用"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="备注" prop="remarks">
              <el-input
                v-model="form.remarks"
                type="textarea"
                :rows="3"
                placeholder="请输入备注"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <!-- 联系方式 -->
      <el-card class="form-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span>联系方式</span>
          </div>
        </template>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="法人代表" prop="legalRepresentative">
              <el-input
                v-model="form.legalRepresentative"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系人" prop="contactName">
              <el-input
                v-model="form.contactName"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="部门" prop="department">
              <el-input
                v-model="form.department"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="微信" prop="wechat">
              <el-input
                v-model="form.wechat"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="网址" prop="website">
              <el-input
                v-model="form.website"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系地址" prop="contactAddress">
    <el-input
                v-model="form.contactAddress"
      placeholder="请输入联系地址"
    />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="公司电话" prop="companyPhone">
              <el-input
                v-model="form.companyPhone"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="contactPhone">
              <el-input
                v-model="form.contactPhone"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="职位" prop="position">
              <el-input
                v-model="form.position"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="contactEmail">
              <el-input
                v-model="form.contactEmail"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <!-- 业务情况 -->
      <el-card class="form-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span>业务情况</span>
          </div>
        </template>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="采购人员" prop="purchaseRepresentativeId">
              <el-input
                v-model="form.purchaseRepresentativeName"
                placeholder="请选择采购人员"
                readonly
                @click="showPersonDialog = true"
              >
                <template #append>
                  <el-button @click="showPersonDialog = true">👤</el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所在部门" prop="purchaseDepartment">
              <el-select
                v-model="form.purchaseDepartment"
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option label="采购部" value="采购部" />
                <el-option label="供应链部" value="供应链部" />
                <el-option label="其他" value="其他" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="业务说明" prop="businessDescription">
              <el-input
                v-model="form.businessDescription"
                type="textarea"
                :rows="3"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <!-- 财务信息 -->
      <el-card class="form-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span>财务信息</span>
          </div>
        </template>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="开户银行" prop="openingBank">
              <el-input
                v-model="form.openingBank"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="银行账号" prop="bankAccount">
              <el-input
                v-model="form.bankAccount"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="网点名称" prop="branchName">
              <el-input
                v-model="form.branchName"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="账户名称" prop="accountName">
              <el-input
                v-model="form.accountName"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="纳税人识别号" prop="taxpayerId">
              <el-input
                v-model="form.taxpayerId"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="税率" prop="taxRate">
              <el-input
                v-model="form.taxRate"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>


    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          确定
        </el-button>
      </span>
    </template>

    <!-- 人员选择对话框 -->
    <PersonDialog v-model="showPersonDialog" @select="handlePersonSelect" />
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import PersonDialog from './PersonDialog.vue'
import BaiduMapSelector from '@/components/BaiduMapSelector.vue'
import {
  addSupplier,
  updateSupplier,
  getAllSupplierLevels,
  getAllSupplierCategories,
  getAllBusinessNatures,
  getAllIndustries,
  getAllLocations
} from '@/Https/server'

// Props
const props = defineProps<{
  modelValue: boolean
  mode: 'add' | 'edit'
  supplier?: any
}>()

// Emits
const emit = defineEmits<{
  'update:modelValue': [value: boolean]
  'success': []
}>()

// 响应式数据
const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => {
    console.log('设置对话框可见性:', value)
    emit('update:modelValue', value)
  }
})

const dialogTitle = computed(() => props.mode === 'add' ? '新增供应商' : '编辑供应商')

const formRef = ref<FormInstance>()
const submitting = ref(false)
const showPersonDialog = ref(false)

// 数据字典
const supplierLevels = ref<any[]>([])
const supplierCategories = ref<any[]>([])
const businessNatures = ref<any[]>([])
const industries = ref<any[]>([])
const locations = ref<any[]>([])

// 加载状态
const loadingDictionary = ref(false)

// 默认数据（当API没有数据时使用）
const defaultSupplierLevels = [
  { id: 1, name: 'A级供应商' },
  { id: 2, name: 'B级供应商' },
  { id: 3, name: 'C级供应商' },
  { id: 4, name: 'D级供应商' }
]

const defaultSupplierCategories = [
  { id: 1, name: '制造商' },
  { id: 2, name: '代理商' },
  { id: 3, name: '贸易商' },
  { id: 4, name: '服务商' },
  { id: 5, name: '其他' }
]

const defaultBusinessNatures = [
  { id: 1, name: '国有企业' },
  { id: 2, name: '民营企业' },
  { id: 3, name: '外资企业' },
  { id: 4, name: '合资企业' },
  { id: 5, name: '个体工商户' }
]

const defaultIndustries = [
  { id: 1, name: '制造业' },
  { id: 2, name: '电子信息' },
  { id: 3, name: '化工材料' },
  { id: 4, name: '机械设备' },
  { id: 5, name: '建筑建材' },
  { id: 6, name: '纺织服装' },
  { id: 7, name: '食品饮料' },
  { id: 8, name: '医药生物' },
  { id: 9, name: '能源环保' },
  { id: 10, name: '其他行业' }
]

const defaultLocations = [
  { id: 1, name: '北京市' },
  { id: 2, name: '上海市' },
  { id: 3, name: '广东省' },
  { id: 4, name: '江苏省' },
  { id: 5, name: '浙江省' },
  { id: 6, name: '山东省' },
  { id: 7, name: '河南省' },
  { id: 8, name: '四川省' },
  { id: 9, name: '湖北省' },
  { id: 10, name: '湖南省' },
  { id: 11, name: '河北省' },
  { id: 12, name: '福建省' },
  { id: 13, name: '陕西省' },
  { id: 14, name: '辽宁省' },
  { id: 15, name: '其他地区' }
]


// 表单数据
const form = reactive({
  id: undefined,
  supplierNumber: '',
  useSystemNumber: true,
  supplierName: '',
  companyName: '',
  supplierLevelId: undefined,
  supplierCategoryId: undefined,
  businessNatureId: 1, // 默认选择第一个营业性质
  industryId: 1, // 默认选择第一个行业
  locationId: 1, // 默认选择第一个地区
  unifiedSocialCreditCode: '',
  isEnabled: true,
  remarks: '',
  contactName: '',
  contactPhone: '',
  contactEmail: '',
  purchaseRepresentativeId: undefined,
  purchaseRepresentativeName: '',
  // 新增字段
  supplierType: 1,
  supplierStatus: 1,
  supplierSource: '',
  cooperationStartDate: null,
  cooperationEndDate: null,
  paymentTerms: undefined,
  creditRating: '',
  isStrategicPartner: false,
  isPreferredSupplier: false,
  companyAddress: '',
  registeredAddress: '',
  registeredCapital: '',
  personnelScale: '',
  // 附件

  // 财务信息
  openingBank: '',
  bankAccount: '',
  branchName: '',
  accountName: '',
  taxpayerId: '',
  taxRate: '',
  // 业务情况
  purchaseDepartment: '',
  businessDescription: '',
  // 联系方式
  legalRepresentative: '',
  department: '',
  wechat: '',
  website: '',
  position: '',
  companyPhone: '',
  contactAddress: ''
})

// 表单验证规则 - 简化版本，去掉正则验证
const rules: FormRules = {
  supplierName: [
    { required: true, message: '请输入供应商名称', trigger: 'blur' }
  ]
}

// 方法
// 并行加载所有数据字典，规范化为 { id, name }，兼容 PageData 大小写
const loadDataDictionary = async () => {
  const normalize = (resp: any, labelKey: string) => {
    const data = resp?.data
    const list = (data?.PageData || data?.pageData || data || []) as any[]
    return (Array.isArray(list) ? list : [])
      .filter((x: any) => x && (x.Id != null || x.id != null))
      .map((x: any) => ({
        id: x.Id ?? x.id,
        name: x[labelKey] ?? x.Name ?? x.name ?? ''
      }))
      .filter((x: any) => x.id && x.name)
  }

  try {
    loadingDictionary.value = true
    console.log('开始加载供应商数据字典...')
    const [levels, categories, natures, inds, locs] = await Promise.all([
      getAllSupplierLevels(),
      getAllSupplierCategories(),
      getAllBusinessNatures(),
      getAllIndustries(),
      getAllLocations()
    ])
    
    // 处理供应商等级数据
    if (levels?.success && levels.data) {
      const normalizedLevels = normalize(levels, 'LevelName')
      supplierLevels.value = normalizedLevels.length > 0 ? normalizedLevels : defaultSupplierLevels
      console.log('供应商等级数据加载成功:', supplierLevels.value)
    } else {
      supplierLevels.value = defaultSupplierLevels
      console.log('使用默认供应商等级数据:', supplierLevels.value)
    }
    
    // 处理供应商类别数据
    if (categories?.success && categories.data) {
      const normalizedCategories = normalize(categories, 'CategoryName')
      supplierCategories.value = normalizedCategories.length > 0 ? normalizedCategories : defaultSupplierCategories
      console.log('供应商类别数据加载成功:', supplierCategories.value)
    } else {
      supplierCategories.value = defaultSupplierCategories
      console.log('使用默认供应商类别数据:', supplierCategories.value)
    }
    
    // 处理营业性质数据
    if (natures?.success && natures.data) {
      const normalizedNatures = normalize(natures, 'NatureName')
      businessNatures.value = normalizedNatures.length > 0 ? normalizedNatures : defaultBusinessNatures
      console.log('营业性质数据加载成功:', businessNatures.value)
    } else {
      businessNatures.value = defaultBusinessNatures
      console.log('使用默认营业性质数据:', businessNatures.value)
    }
    
    // 处理行业数据
    if (inds?.success && inds.data) {
      const normalizedIndustries = normalize(inds, 'IndustryName')
      industries.value = normalizedIndustries.length > 0 ? normalizedIndustries : defaultIndustries
      console.log('行业数据加载成功:', industries.value)
    } else {
      industries.value = defaultIndustries
      console.log('使用默认行业数据:', industries.value)
    }
    
    // 处理地区数据
    if (locs?.success && locs.data) {
      const normalizedLocations = normalize(locs, 'LocationName')
      locations.value = normalizedLocations.length > 0 ? normalizedLocations : defaultLocations
      console.log('地区数据加载成功:', locations.value)
    } else {
      locations.value = defaultLocations
      console.log('使用默认地区数据:', locations.value)
    }
    
    console.log('所有数据字典加载完成')
  } catch (error) {
    console.error('加载数据字典失败，使用默认数据:', error)
    
    // 使用默认数据作为兜底
    supplierLevels.value = defaultSupplierLevels
    supplierCategories.value = defaultSupplierCategories
    businessNatures.value = defaultBusinessNatures
    industries.value = defaultIndustries
    locations.value = defaultLocations
    
    console.log('已设置默认数据作为兜底')
  } finally {
    loadingDictionary.value = false
  }
}

const resetForm = () => {
  Object.assign(form, {
    id: undefined,
    supplierNumber: '',
    useSystemNumber: true,
    supplierName: '',
    companyName: '',
    supplierLevelId: undefined,
    supplierCategoryId: undefined,
    businessNatureId: 1, // 默认选择第一个营业性质
    industryId: 1, // 默认选择第一个行业
    locationId: 1, // 默认选择第一个地区
    unifiedSocialCreditCode: '',
    isEnabled: true,
    remarks: '',
    contactName: '',
    contactPhone: '',
    contactEmail: '',
    purchaseRepresentativeId: undefined,
    purchaseRepresentativeName: '',
    // 新增字段
    supplierType: 1, // SupplierType.Manufacturer
    supplierStatus: 1, // SupplierStatus.Active
    supplierSource: '',
    cooperationStartDate: null,
    cooperationEndDate: null,
    paymentTerms: undefined,
    creditRating: '',
    isStrategicPartner: false,
    isPreferredSupplier: false,
    companyAddress: '',
    registeredAddress: '',
    registeredCapital: '',
    personnelScale: '',
    // 财务信息
    openingBank: '',
    bankAccount: '',
    branchName: '',
    accountName: '',
    taxpayerId: '',
    taxRate: '',
    // 业务情况
    purchaseDepartment: '',
    businessDescription: '',
    // 联系方式
    legalRepresentative: '',
    department: '',
    wechat: '',
    website: '',
    position: '',
    companyPhone: '',
    contactAddress: ''
  })
  
  // 如果是新增模式，自动生成供应商编号
  if (props.mode === 'add') {
    nextTick(() => {
      generateSupplierNumber()
    })
  }
}

const handleClose = () => {
  dialogVisible.value = false
  resetForm()
}

const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    // 简化验证，只验证供应商名称
    await formRef.value.validate()
    submitting.value = true

    const submitData = { ...form }
    
    // 如果是新增且使用系统编号，则不传供应商编号
    if (props.mode === 'add' && form.useSystemNumber) {
      delete submitData.supplierNumber
    }
    
    // 确保必填字段有默认值
    if (!submitData.businessNatureId) {
      submitData.businessNatureId = 1
    }
    if (!submitData.supplierType) {
      submitData.supplierType = 1
    }
    if (!submitData.supplierStatus) {
      submitData.supplierStatus = 1
    }

    // 数据清理和转换
    const cleanData = (value: any) => {
      if (value === null || value === undefined || value === '') {
        return null
      }
      return value
    }

    // 确保字段名称与后端DTO匹配，使用PascalCase字段名，并进行数据清理
    const mappedData = {
      Id: cleanData(submitData.id),
      SupplierNumber: cleanData(submitData.supplierNumber),
      SupplierName: cleanData(submitData.supplierName),
      CompanyName: cleanData(submitData.companyName),
      SupplierLevelId: cleanData(submitData.supplierLevelId),
      SupplierCategoryId: cleanData(submitData.supplierCategoryId),
      BusinessNatureId: submitData.businessNatureId || 1, // 确保有默认值
      IndustryId: cleanData(submitData.industryId),
      LocationId: cleanData(submitData.locationId),
      UnifiedSocialCreditCode: cleanData(submitData.unifiedSocialCreditCode),
      IsEnabled: submitData.isEnabled !== undefined ? submitData.isEnabled : true,
      Remarks: cleanData(submitData.remarks),
      ContactName: cleanData(submitData.contactName),
      ContactPhone: cleanData(submitData.contactPhone),
      ContactEmail: cleanData(submitData.contactEmail),
      PurchaseRepresentativeId: cleanData(submitData.purchaseRepresentativeId),
      SupplierType: submitData.supplierType || 1, // 确保有默认值
      SupplierStatus: submitData.supplierStatus || 1, // 确保有默认值
      SupplierSource: cleanData(submitData.supplierSource),
      CooperationStartDate: cleanData(submitData.cooperationStartDate),
      CooperationEndDate: cleanData(submitData.cooperationEndDate),
      PaymentTerms: cleanData(submitData.paymentTerms),
      CreditRating: cleanData(submitData.creditRating),
      IsStrategicPartner: submitData.isStrategicPartner !== undefined ? submitData.isStrategicPartner : false,
      IsPreferredSupplier: submitData.isPreferredSupplier !== undefined ? submitData.isPreferredSupplier : false,
      CompanyAddress: cleanData(submitData.companyAddress),
      RegisteredAddress: cleanData(submitData.registeredAddress),
      RegisteredCapital: cleanData(submitData.registeredCapital),
      PersonnelScale: cleanData(submitData.personnelScale),
      
      // 财务信息
      OpeningBank: cleanData(submitData.openingBank),
      BankAccount: cleanData(submitData.bankAccount),
      BranchName: cleanData(submitData.branchName),
      AccountName: cleanData(submitData.accountName),
      TaxpayerId: cleanData(submitData.taxpayerId),
      TaxRate: cleanData(submitData.taxRate),
      
      // 业务情况
      PurchaseDepartment: cleanData(submitData.purchaseDepartment),
      BusinessDescription: cleanData(submitData.businessDescription),
      
      // 联系方式
      LegalRepresentative: cleanData(submitData.legalRepresentative),
      Department: cleanData(submitData.department),
      Wechat: cleanData(submitData.wechat),
      Website: cleanData(submitData.website),
      Position: cleanData(submitData.position),
      CompanyPhone: cleanData(submitData.companyPhone),
      ContactAddress: cleanData(submitData.contactAddress)
    }

    console.log('提交数据:', mappedData)

    const response = props.mode === 'add' 
      ? await addSupplier(mappedData)
      : await updateSupplier(mappedData)

    if (response.success) {
      ElMessage.success(props.mode === 'add' ? '新增成功' : '更新成功')
      emit('success')
    } else {
      ElMessage.error(response.message || '操作失败')
    }
  } catch (error) {
    console.error('提交失败:', error)
    
    // 提供更详细的错误信息
    if (error.response) {
      // 服务器响应了错误状态码
      const status = error.response.status
      const message = error.response.data?.message || error.response.data?.Message || '服务器错误'
      
      if (status === 400) {
        ElMessage.error(`请求参数错误: ${message}`)
      } else if (status === 401) {
        ElMessage.error('未授权，请重新登录')
      } else if (status === 403) {
        ElMessage.error('权限不足')
      } else if (status === 404) {
        ElMessage.error('请求的资源不存在')
      } else if (status === 500) {
        ElMessage.error(`服务器内部错误: ${message}`)
      } else {
        ElMessage.error(`请求失败 (${status}): ${message}`)
      }
    } else if (error.request) {
      // 请求已发出但没有收到响应
      ElMessage.error('网络连接失败，请检查网络连接')
    } else {
      // 其他错误
      ElMessage.error(`提交失败: ${error.message || '未知错误'}`)
    }
  } finally {
    submitting.value = false
  }
}

const handlePersonSelect = (person: any) => {
  form.purchaseRepresentativeId = person.id
  form.purchaseRepresentativeName = person.name
  showPersonDialog.value = false
}

// 处理公司地址选择
const handleCompanyAddressSelected = (location: { address: string; lng: number; lat: number }) => {
  form.companyAddress = location.address
  console.log('公司地址已选择:', location)
}

// 处理注册地址选择
const handleRegisteredAddressSelected = (location: { address: string; lng: number; lat: number }) => {
  form.registeredAddress = location.address
  console.log('注册地址已选择:', location)
}

// 处理联系地址选择
const handleContactAddressSelected = (location: { address: string; lng: number; lat: number }) => {
  form.contactAddress = location.address
  console.log('联系地址已选择:', location)
}

// 处理系统编号复选框变化
const handleSystemNumberChange = (checked: boolean) => {
  if (checked) {
    // 如果启用系统编号，自动生成一个编号
    generateSupplierNumber()
  } else {
    // 如果禁用系统编号，清空编号
    form.supplierNumber = ''
  }
}

// 生成供应商编号
const generateSupplierNumber = () => {
  if (!form.useSystemNumber) {
    ElMessage.warning('请先启用系统编号')
    return
  }
  
  // 生成格式：SUP + 年月日 + 4位随机数
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  const random = Math.floor(Math.random() * 10000).toString().padStart(4, '0')
  
  form.supplierNumber = `SUP${year}${month}${day}${random}`
  ElMessage.success('供应商编号生成成功')
}




// 监听供应商数据变化
watch(() => props.supplier, (newSupplier) => {
  if (newSupplier && props.mode === 'edit') {
    console.log('编辑模式，加载供应商数据:', newSupplier)
    
    // 兼容后端 PascalCase 与前端 camelCase 的字段名
    const safeGet = (obj: any, key: string, defaultValue: any = '') => {
      if (!obj) return defaultValue
      if (obj[key] !== undefined && obj[key] !== null) return obj[key]
      const pascalKey = key.charAt(0).toUpperCase() + key.slice(1)
      if (obj[pascalKey] !== undefined && obj[pascalKey] !== null) return obj[pascalKey]
      return defaultValue
    }
    
    // 确保字典已加载后再赋值
    // 映射字段名称
    Object.assign(form, {
      id: safeGet(newSupplier, 'id'),
      supplierNumber: safeGet(newSupplier, 'supplierNumber'),
      supplierName: safeGet(newSupplier, 'supplierName'),
      companyName: safeGet(newSupplier, 'companyName'),
      supplierLevelId: safeGet(newSupplier, 'supplierLevelId'),
      supplierCategoryId: safeGet(newSupplier, 'supplierCategoryId'),
      businessNatureId: safeGet(newSupplier, 'businessNatureId'),
      industryId: safeGet(newSupplier, 'industryId'),
      locationId: safeGet(newSupplier, 'locationId'),
      unifiedSocialCreditCode: safeGet(newSupplier, 'unifiedSocialCreditCode'),
      isEnabled: safeGet(newSupplier, 'isEnabled', true),
      remarks: safeGet(newSupplier, 'remarks'),
      contactName: safeGet(newSupplier, 'contactName'),
      contactPhone: safeGet(newSupplier, 'contactPhone'),
      contactEmail: safeGet(newSupplier, 'contactEmail'),
      purchaseRepresentativeId: safeGet(newSupplier, 'purchaseRepresentativeId'),
      purchaseRepresentativeName: safeGet(newSupplier, 'purchaseRepresentativeName'),
      // 新增字段映射
      supplierType: safeGet(newSupplier, 'supplierType', 1),
      supplierStatus: safeGet(newSupplier, 'supplierStatus', 1),
      supplierSource: safeGet(newSupplier, 'supplierSource'),
      cooperationStartDate: safeGet(newSupplier, 'cooperationStartDate'),
      cooperationEndDate: safeGet(newSupplier, 'cooperationEndDate'),
      paymentTerms: safeGet(newSupplier, 'paymentTerms'),
      creditRating: safeGet(newSupplier, 'creditRating'),
      isStrategicPartner: safeGet(newSupplier, 'isStrategicPartner', false),
      isPreferredSupplier: safeGet(newSupplier, 'isPreferredSupplier', false),
      companyAddress: safeGet(newSupplier, 'companyAddress', safeGet(newSupplier, 'registeredAddress', '')),
      registeredAddress: safeGet(newSupplier, 'registeredAddress'),
      registeredCapital: safeGet(newSupplier, 'registeredCapital'),
      personnelScale: safeGet(newSupplier, 'personnelScale', safeGet(newSupplier, 'personnelScaleId', '')),
      // 财务信息
      openingBank: safeGet(newSupplier, 'openingBank'),
      bankAccount: safeGet(newSupplier, 'bankAccount'),
      branchName: safeGet(newSupplier, 'branchName'),
      accountName: safeGet(newSupplier, 'accountName', safeGet(newSupplier, 'companyName', '')),
      taxpayerId: safeGet(newSupplier, 'taxpayerId', safeGet(newSupplier, 'unifiedSocialCreditCode', '')),
      taxRate: safeGet(newSupplier, 'taxRate'),
      // 业务情况
      purchaseDepartment: safeGet(newSupplier, 'purchaseDepartment', safeGet(newSupplier, 'department', '')),
      businessDescription: safeGet(newSupplier, 'businessDescription'),
      // 联系方式
      legalRepresentative: safeGet(newSupplier, 'legalRepresentative'),
      department: safeGet(newSupplier, 'department'),
      wechat: safeGet(newSupplier, 'wechat'),
      website: safeGet(newSupplier, 'website'),
      position: safeGet(newSupplier, 'position'),
      companyPhone: safeGet(newSupplier, 'companyPhone', safeGet(newSupplier, 'contactPhone', '')),
      contactAddress: safeGet(newSupplier, 'contactAddress', safeGet(newSupplier, 'companyAddress', ''))
    })

    // 智能兜底：进一步填充关键字段，避免编辑时为空
    if (!form.legalRepresentative && form.contactName) form.legalRepresentative = form.contactName
    if (!form.contactName && form.legalRepresentative) form.contactName = form.legalRepresentative
    if (!form.purchaseDepartment && form.department) form.purchaseDepartment = form.department
    if (!form.companyPhone && form.contactPhone) form.companyPhone = form.contactPhone
    if (!form.contactAddress && form.companyAddress) form.contactAddress = form.companyAddress
    if (!form.accountName && form.companyName) form.accountName = form.companyName
    if (!form.taxpayerId && form.unifiedSocialCreditCode) form.taxpayerId = form.unifiedSocialCreditCode
    if (!form.businessDescription && form.supplierName) form.businessDescription = `${form.supplierName} 业务合作`
    if (!form.personnelScale) form.personnelScale = '1'
    if (!form.openingBank) form.openingBank = '待完善'
    if (!form.branchName) form.branchName = '待完善'
    if (!form.bankAccount) form.bankAccount = '待完善'
    if (!form.taxRate) form.taxRate = '13'
    if (!form.wechat) form.wechat = '请完善'
    if (!form.website) form.website = 'http://'
  }
}, { immediate: true })

// 生命周期
onMounted(async () => {
  await loadDataDictionary()
})
</script>

<style scoped>
.supplier-form {
  max-height: 70vh;
  overflow-y: auto;
}

.form-card {
  margin-bottom: 20px;
}

.card-header {
  font-weight: 600;
  color: #333;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style> 